package cn.xk.user.service.impl;

import cn.xk.basic.exception.BusinessException;
import cn.xk.basic.service.impl.BaseServiceImpl;
import cn.xk.basic.util.AjaxResult;
import cn.xk.basic.util.HttpUtil;
import cn.xk.basic.util.Md5Utils;
import cn.xk.basic.util.StrUtils;
import cn.xk.jwt.JwtUtils;
import cn.xk.jwt.LoginData;
import cn.xk.jwt.RsaUtils;
import cn.xk.sys.domain.Menu;
import cn.xk.user.constant.WxConstants;
import cn.xk.user.domain.Logininfo;
import cn.xk.user.domain.User;
import cn.xk.user.domain.Wxuser;
import cn.xk.user.dto.LoginDto;
import cn.xk.user.mapper.LogininfoMapper;
import cn.xk.user.mapper.UserMapper;
import cn.xk.user.mapper.WxuserMapper;
import cn.xk.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import jdk.nashorn.internal.parser.Token;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        //1.检验空值
        if (StringUtils.isEmpty(loginDto.getAccount()) || StringUtils.isEmpty(loginDto.getCheckPass())) {
            throw new BusinessException("信息不能为空!!!");
        }
        //2.检验账号
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) {//没有查到账号
            throw new BusinessException("账号错误");
        }
        //3.校验密码
        String inputMd5Pwd = Md5Utils.encrypByMd5(loginDto.getCheckPass() + logininfo.getSalt());
        if (!inputMd5Pwd.equals(logininfo.getPassword())) {
            throw new BusinessException("密码错误!!!");
        }
        //4.校验是否禁用
        if (!logininfo.getDisable()) {
            throw new BusinessException("该账号被禁用，请联系管理员!!!");
        }
        return loginSuccessJwtHandler(logininfo);

    }

    @Override
    public AjaxResult wechatLogin(Map<String, String> map) {
        //发送第二个请求：需要code，appid，secret 返回token，openid
        //第二个请求地址
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", map.get("code"));
        //2.使用HttpUtil发送微信登录请求：第二个请求,返回json格式字符串
        String jsonStr = HttpUtil.httpGet(url);
        //3.通过fastJson将json格式的字符串转成json对象：为了获取token和openid
        JSONObject jsonObj = JSONObject.parseObject(jsonStr);
        String access_token = jsonObj.getString("access_token");
        String openid = jsonObj.getString("openid");
        //4.通过openid查t_wxuser表
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);
        //4.1查到了就免密登录：返回true，token和logininfo对象
        if (wxuser != null) {
            //绑定过
            //根据user_id有可能查询到信息
            User user = userMapper.loadById(wxuser.getUserId());
            if (user != null) {
                //绑定user
                Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
                Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
                return AjaxResult.me().setObj(resultMap);

            }

        }
        //没查到过第一次扫码加token和openid响应给前端 - 到绑定页面进行绑定
        return AjaxResult.me().setSuccess(false).setObj("?access_token=" + access_token + "&openid=" + openid);
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验-空值
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空!!!");
        }
        //2.校验-手机验证码：是否过期，是否正确:【业务键:电话号码 - 手机验证码:时间戳】
        Object obj = redisTemplate.opsForValue().get("binder:" + phone);
        if (obj == null) {
            throw new BusinessException("手机验证码过期!!!");
        }
        if (!verifyCode.equals(obj.toString().split(":")[0])) {
            throw new BusinessException("手机验证码错误!!!");
        }
        //3.准备第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        //4.使用HttpUtil发送微信绑定请求-获取微信用户信息：返回jsonStr
        String jsonStr = HttpUtil.httpGet(url);
        //5.使用fastJson处理jsonStr-将jsonObj的数据转换Wxuser对象
        Wxuser wxuser = jsonStr2WxUser(jsonStr);
        //6.创建User对象和Logininfo对象
        //1.以前通过手机账号注册过,没有绑定微信
        User user = userMapper.loadByPhone(phone);
        if (user == null) {
            //手机号码没有绑定
            user = phone2User(phone);
            Logininfo newLogininfo = user2Loginfo(user);
            logininfoMapper.save(newLogininfo);
            user.setLogininfoId(newLogininfo.getId());
            userMapper.save(user);
        }
        //微信用户绑定User
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);
        //7.添加数据库 Logininfo对象 - User对象 - WxUser对象
        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());
        Map<String, Object> resultMap = loginSuccessJwtHandler(logininfo);
        return AjaxResult.me().setObj(resultMap);


    }

    private Logininfo user2Loginfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        logininfo.setDisable(true);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String pwd = StrUtils.getComplexRandomString(12);
        String md5Pwd = Md5Utils.encrypByMd5(pwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);
        return user;
    }

    private Wxuser jsonStr2WxUser(String jsonStr) {
        JSONObject obj = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(obj.getString("openid"));
        wxuser.setNickname(obj.getString("nickname"));
        wxuser.setHeadimgurl(obj.getString("headimgurl"));
        wxuser.setUnionid(obj.getString("unionid"));
        return wxuser;
    }

    public Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        //传递给前端
        Map<String, Object> map = new HashMap<>();
        //使用jwt加密
        LoginData loginData = new LoginData();
        //1.设置logininfo
        logininfo.setSalt(null);
        logininfo.setPassword(null);
        map.put("logininfo", logininfo);
        loginData.setLogininfo(logininfo);
        //2.设置permissions,menus-管理员
        if (logininfo.getType() == 0) {
            //设置permissions即权限
            List<String> permissions = logininfoMapper.findPermissionsByLogininfoId(logininfo.getId());
            map.put("permissions", permissions);

            loginData.setPermissions(permissions);
            //设置menus
            List<Menu> menus = logininfoMapper.findMenusByLogininfoId(logininfo.getId());
            map.put("menus", menus);
            loginData.setMenus(menus);
        }
        //3.设置jwtToken-加密-loginData

        try {
            PrivateKey privateKey = RsaUtils.getPrivateKey(RsaUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            //设置私钥登录数据，时限为30分钟
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30);
            map.put("token", jwtToken);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }
}
